import { type Component, createResource, createSignal, Show } from "solid-js";
import Game from "./components/game2/game.tsx";
import { useFullscreen } from "solidjs-use";

const fileHandler = async (file: File) => {
  if (!file) return [];

  const str = await file.text();

  return JSON.parse(str);
};
const App: Component = () => {
  const [started, setStarted] = createSignal<boolean>(false);
  const [teams, setTeams] = createSignal<number>(2);
  const [vocabularyFile, setVocabularyFile] = createSignal<File | null>(null);

  const [vocabularies] = createResource(vocabularyFile, fileHandler);

  const { toggle: toggleFullScreen, isSupported: isFullscreenSupported } =
    useFullscreen();

  function ConfigPage() {
    return (
      <dialog open class="modal">
        <div class="modal-box">
          <form>
            <fieldset class="fieldset">
              <legend class="fieldset-legend">Teams</legend>
              <input
                type="number"
                min={1}
                max={10}
                class="input"
                placeholder="Number of Teams"
                value={teams()}
                onChange={(e) =>
                  setTeams(Math.round(Math.max(+e.target.value, 0)) || 0)}
              />
            </fieldset>

            <fieldset class="fieldset">
              <legend class="fieldset-legend">加载词汇</legend>
              <input
                type="file"
                accept=".json"
                class="file-input"
                onChange={(e) => setVocabularyFile(e.target.files?.[0] || null)}
              />
            </fieldset>
          </form>
          <div class="modal-action">
            <form method="dialog">
              <button
                type="button"
                class="btn btn-primary"
                disabled={vocabularies.loading || !vocabularies() && !!teams()}
                onClick={() => setStarted(true)}
              >
                START
              </button>
            </form>
          </div>
        </div>
      </dialog>
    );
  }

  return (
    <>
      <Show when={started()} fallback={<ConfigPage />}>
        <div class="w-screen h-screen">
          <Game teams={teams()} vocabularies={vocabularies()}></Game>
        </div>
      </Show>
      <button
        class="fixed top-4 right-4 btn"
        type="button"
        disabled={!isFullscreenSupported()}
        onClick={toggleFullScreen}
      >
        Full Screen
      </button>
    </>
  );
};

export default App;
